// lib/services/stock_api_service.dart
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:gbk_codec/gbk_codec.dart';

class StockListService extends GetxService {
  final Dio _dio = Dio();

  static const String baseUrl = 'https://hq.sinajs.cn';

  @override
  void onInit() {
    super.onInit();
    // 配置Dio拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) {
          // 添加请求头，避免被新浪阻止
          options.headers['Referer'] = 'https://finance.sina.com.cn';
          options.headers['User-Agent'] =
          'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
          return handler.next(options);
        },
      ),
    );
  }

  // 将数据库格式的代码转换为新浪API格式
  String _convertToSinaSymbol(String dbSymbol) {
    // 数据库格式: sh.600000 -> 新浪格式: sh600000
    return dbSymbol.replaceAll('.', '');
  }

  // 将新浪API格式的代码转换回数据库格式
  String _convertToDbSymbol(String sinaSymbol) {
    // 新浪格式: sh600000 -> 数据库格式: sh.600000
    if (sinaSymbol.length > 2) {
      return '${sinaSymbol.substring(0, 2)}.${sinaSymbol.substring(2)}';
    }
    return sinaSymbol;
  }

  // 获取股票数据
  Future<Map<String, String>> fetchStockData(List<String> dbSymbols) async {
    try {
      // 转换代码格式
      final sinaSymbols = dbSymbols.map(_convertToSinaSymbol).toList();

      final response = await _dio.get(
        '$baseUrl/list=${sinaSymbols.join(",")}',
        options: Options(responseType: ResponseType.bytes),
      );

      if (response.statusCode == 200) {
        // 新浪API返回的数据格式为多行，每行格式：var hq_str_sh601006="大秦铁路,6.890,6.920,...";
        String data = gbk_bytes.decode(response.data);

        print("sina股票代码:$data");
        print('Requesting URL: $baseUrl/list=${sinaSymbols.join(",")}');

        // 解析多股票数据
        final lines = data.split('\n');
        final Map<String, String> result = {};

        for (final line in lines) {
          if (line.isEmpty) continue;

          // 提取股票代码和数据
          final symbolMatch = RegExp(r'hq_str_(\w+)=').firstMatch(line);
          if (symbolMatch != null) {
            final sinaSymbol = symbolMatch.group(1);
            final dataStart = line.indexOf('="') + 2;
            final dataEnd = line.lastIndexOf('"');

            if (dataStart > 2 && dataEnd > dataStart) {
              final stockData = line.substring(dataStart, dataEnd);
              // 转换回数据库格式的代码
              final dbSymbol = _convertToDbSymbol(sinaSymbol!);
              result[dbSymbol] = stockData;
            }
          }
        }

        return result;
      } else {
        throw Exception('Failed to load stock data');
      }
    } catch (e) {
      throw Exception('获取股票数据失败: $e');
    }
  }
}